import time
import copy
import view.work_order as view_wo
import dao.work_order_dao as dao
import dao.common_dao as common_dao
import dao.user_dao as user_dao
import dao.shop_dao as shop_dao
import dao.topic_dao as topic_dao
import dao.user_resource_dao as user_resource_dao
import dao.work_order_extend_dao as work_order_extend_dao
import dao.strategy_dao as strategy_dao
import model.model as ut
from utils.common.time_util import get_after_timestamp_ms
from exception.api_exception import APIException
from enums.work_order_status_enum import WorkOrderStatusEnum
from enums.work_order_type_enum import WorkOrderTypeEnum


def details(req_params: view_wo.Details, cur_user_id: int):
    """
    工单-查询详情
    :param req_params:
    :param cur_user_id:
    :return:
    """
    # 通过条件查询工单信息
    total, cur_list = dao.query_work_order_by_page(req_params, cur_user_id)
    user_ids = []
    ids = []
    for item in cur_list:
        user_ids.append(item.make_user_id)
        user_ids.append(item.get_user_id)
        ids.append(item.id)
    # 查询对应的user
    total_count, shops = shop_dao.query_shops_all()
    shop_dict = dict()
    for i in shops:
        shop_dict[i.id] = i.shop_name
    users = user_dao.query_user_by_ids(user_ids)
    user_dict = dict()
    for i in users:
        user_dict[i.id] = i.name_zh
    # 提交成功的对象
    submitted_counts = topic_dao.search_submitted_by_work_orders(ids)
    id_count_dict = dict()
    for sub_c_i in submitted_counts:
        inner_wo_id = sub_c_i.work_order_id
        count = sub_c_i.count
        id_count_dict[inner_wo_id] = count
    ll = []  # 返回的结果对象
    for i in cur_list:
        # 查询用户名称
        ger_user_name = ""
        if i.get_user_id and user_dict.get(i.get_user_id):
            ger_user_name = user_dict.get(i.get_user_id)
        make_user_name = ""
        if i.make_user_id and user_dict.get(i.make_user_id):
            make_user_name = user_dict.get(i.make_user_id)
        shop_name = ""
        if i.shop_id and shop_dict.get(i.shop_id):
            shop_name = shop_dict.get(i.shop_id)
        # 查询已提交份数
        submitted_count = id_count_dict.get(i.id) or 0  # 提交成功的对象
        # submitted_count = topic_dao.search_by_work_order_id_submitted(i.id)  # 提交成功的对象
        # submitted_failed_count = topic_dao.search_by_work_order_id_submit_failed(i.id)  # 提交失败的数量
        # 封装返回对象
        ll.append({'id': i.id, 'ww': i.ww, 'order_id': i.order_id, 'make_user_id': i.make_user_id,
                   'make_user_name': make_user_name, 'get_user_id': i.get_user_id, 'shop_name': shop_name,
                   'get_user_name': ger_user_name, 'cost': i.cost, 'total_size': i.total_size, 'shop_id': i.shop_id,
                   'link': i.link, 'priority': i.priority, 'bz': i.bz, 'status': i.status, 'feedback': i.feedback,
                   'oper_type': i.oper_type, 'submitted_count': submitted_count,
                   # 'submitted_failed_count': submitted_failed_count,
                   'plan_finished_time': i.plan_finished_time, 'ordered_time': i.ordered_time,
                   'area_note': i.area_note, 'refund_amount': i.refund_amount})
    res = {'total': total, 'datas': ll}
    return res


def document_making_billboard(user_id: int):
    user_count, all_users = user_dao.query_user_all()
    cur_list = []
    for i in all_users:
        total_count = dao.query_by_user_id(i.id)
        cur_list.append({'user_name': i.user_name, 'user_nam_zh': i.name_zh, 'count': total_count})
    return {'datas': cur_list, 'count': len(cur_list)}


def dashboard(req_params):
    order_type = req_params.get('order_type')
    shop_id = req_params.get('shop_id')
    orders, users = dao.dashboard(req_params)
    shop_name = '全部'
    if shop_id:
        shop_obj = shop_dao.query_shops_by_id(int(shop_id))
        if shop_obj:
            shop_name = shop_obj.shop_name or ''
        else:
            raise APIException(message='门店不存在')
    user_tmp = {}
    for user in users:
        user_tmp[user.id] = {
            # 总份数
            'total_size': 0.0,
            # 总金额
            'total_cost': 0.0,
            # 退款金额
            'charge_back': 0.0,
            # 中文名
            'name_zh': user.name_zh,
            'shop_name': shop_name
        }
    for order in orders:
        # 制单还是接单
        try:
            user_id = order.make_user_id if order_type == 'get' else order.get_user_id
            if order.status == 7:
                if isinstance(order.cost, str):
                    user_tmp[user_id]['charge_back'] = round(user_tmp[user_id]['charge_back'] + float(order.cost), 2)
            else:
                if isinstance(order.total_size, str):
                    # user_tmp[user_id]['total_size'] = round(user_tmp[user_id]['total_size'] + int(order.total_size), 2)
                    user_tmp[user_id]['total_size'] = round(user_tmp[user_id]['total_size'] + 1, 2)
                if isinstance(order.cost, str):
                    user_tmp[user_id]['total_cost'] = round(user_tmp[user_id]['total_cost'] + int(order.cost), 2)
        except Exception as e:
            print(e)
    return list(user_tmp.values())


def create_virtual_order(link: str, size, user_id, note, work_order_type):
    sys_virtual = 'sys_virtual'
    history_work_order_item = None
    # 如果是问卷星vj开头的问卷，则替换成vm
    if link.startswith('https://www.wjx.cn/vj/'):
        link = link.replace("/vj/", "/vm/", 1)
    if link:
        history_work_order_item = dao.query_by_link(link)
    now = int(time.time() * 1000)
    new_work_order = ut.WorkOrder(ww=sys_virtual, order_id=0, make_user_id=user_id, get_user_id=user_id, cost=0,
                                  total_size=size, shop_id=0, link=link, priority=0, bz=note, status=1,
                                  oper_type=0, plan_finished_time=get_after_timestamp_ms(now, 6 * 60 * 60),
                                  ordered_time=now, work_order_type=WorkOrderTypeEnum.VIRTUAL.value)
    dao.commit_obj(new_work_order)
    if history_work_order_item:  # 如果有历史配置，则同步历史配置
        copy_history_work_order_config(history_work_order_item, new_work_order)
    return {'work_order_id': new_work_order.id}


def chargeback(cur_user_id, work_order_id, refund_amount):
    # 当前工单制单人才能操作退款
    work_order = dao.query_work_order_by_id(id=work_order_id)
    if not work_order:
        raise APIException(message="工单不存在")
    # if cur_user_id != work_order.make_user_id: # 沟通后，所有人都可以发起退款
    #     raise APIException(message="当前登录用户非工单制单人，无法发起退款")
    if work_order.status == WorkOrderStatusEnum.SENDING.value:
        raise APIException(message="当前工单正在发送中，无法发起退款")
    work_order = dao.query_work_order_by_id(id=work_order_id)
    work_order.status = WorkOrderStatusEnum.CHARGEBACK.value
    work_order.refund_amount = round(refund_amount, 2)
    dao.commit_obj(work_order)
    return


def user_auth(user_id):
    # 查询当前用户的权限
    res = dict()
    res['resource_ids'] = ""
    user_resources = user_resource_dao.search_by_user_id(user_id)
    if not user_resources:
        raise APIException(message="当前用户暂无权限")
    resource_ids = [i.resource_id for i in user_resources]
    res['resource_ids'] = resource_ids
    return res


def create_order(i, cur_user_id):
    # 生成数据
    custom_order_id = i.get('order_id')  # 订单号
    get_user_id = i.get('get_user_id')  # 用户id
    # make_user_id = i.get('make_user_id')  # 用户id
    custom_name = i.get('custom_name')  # 客户名称
    work_order_type = i.get('work_order_type')  # 订单类型，虚拟订单还是普通订单
    cur_link = i.get('link')  # 问卷链接
    # 如果是问卷星vj开头的问卷，则替换成vm
    if cur_link.startswith('https://www.wjx.cn/vj/'):
        cur_link = cur_link.replace("/vj/", "/vm/", 1)
    history_work_order_item = None
    if cur_link:
        history_work_order_item = dao.query_by_link(cur_link)  # 提前查询这个链接最新的工单
    now = int(time.time() * 1000)
    # transcribe_user_id = i.get('make_user_id')
    make_id = i.get('make_user_id')
    if not make_id:
        make_id = cur_user_id
    # 新工单对象
    new_work_order = ut.WorkOrder(ww=custom_name, order_id=custom_order_id, make_user_id=make_id,
                                  get_user_id=get_user_id, cost=i.get('cost'), total_size=i.get('size'),
                                  shop_id=i.get('shop_id'), link=i.get('link'), priority=i.get('priority'),
                                  bz=i.get('bz'), status=0, oper_type=i.get('oper_type'),
                                  plan_finished_time=get_after_timestamp_ms(now, 6 * 60 * 60), ordered_time=now,
                                  area_note=i.get('area_note'), work_order_type=WorkOrderTypeEnum.NORMAL.value,
                                  transcribe_user_id=make_id)
    dao.commit_obj(new_work_order)
    if history_work_order_item:  # 如果有历史工单，则将历史工单的配置配置到新的工单上面
        copy_history_work_order_config(history_work_order_item, new_work_order)
    return


def copy_history_work_order_config(history_work_order_item, new_work_order):
    # 如果找到了历史工单，根据历史工单查询所有数据进行复制
    history_wo_id = history_work_order_item.id
    new_work_order_id = new_work_order.id
    if history_wo_id:
        # 1.复制链接解析的配置
        # woe_item = work_order_extend_dao.search_by_work_order_id(history_wo_id)
        # if woe_item:
        #     new_woe = copy.deepcopy(woe_item)
        #     new_woe.id = None  # 主键删除
        #     new_woe.work_order_id = new_work_order_id  # 关联新工单
        #     common_dao.add_commit(new_woe)
        # 2.复制权重配置、方案配置、相关配置、提交配置
        s_item = strategy_dao.search_by_work_order_id(history_wo_id)
        if s_item:
            t = ut.Strategy()
            t.work_order_id = new_work_order_id
            t.strategy_weight = s_item.strategy_weight
            t.strategy_programme = s_item.strategy_programme
            t.relation_config = s_item.relation_config
            t.submit_config = s_item.submit_config
            common_dao.add_commit(t)
        # 3.复制链接解析的配置
        woe_item = work_order_extend_dao.search_by_work_order_id(history_wo_id)
        if woe_item:
            t = ut.WorkOrderExtend()
            t.work_order_id = new_work_order_id
            t.titles = woe_item.titles
            t.title_maps = woe_item.title_maps
            common_dao.add_commit(t)


def submit():
    total, cur_list = dao.query_work_order_by_page(2, 1)
    return {'total': total, 'datas': cur_list}


def get_users_make_get(cur_user_id: int):
    """
    获取制单人和接单人列表
    :return:
    """
    user_resources = user_resource_dao.search_by_resource_ids([1, 2])  # 查询资源类型为1和2的所有用户
    user_ids1 = []  # 制单人
    user_ids2 = []  # 接单人
    for i in user_resources:
        if i.resource_id == 1:
            user_ids1.append(i.user_id)
        if i.resource_id == 2:
            user_ids2.append(i.user_id)
    get_users = []
    make_users = []
    users1 = user_dao.query_user_by_ids(user_ids1)
    users2 = user_dao.query_user_by_ids(user_ids2)
    for i in users1:
        d = dict()
        d['id'] = i.id
        d['name'] = i.name_zh
        get_users.append(d)
    for i in users2:
        d = dict()
        d['id'] = i.id
        d['name'] = i.name_zh
        make_users.append(d)
    res = dict()
    res['get_users'] = get_users
    res['make_users'] = make_users
    return res


def get_users():
    total, cur_list = user_dao.query_user_all()
    datas = []
    for i in cur_list:
        datas.append({'id': i.id, 'name': i.name_zh})
    return {'total': total, 'datas': datas}


def delete_shop(shop_id: int):
    """
    删除店铺信息
    :param shop_id: 店铺id
    :return:
    """
    shop_dao.delete_by_id(id=shop_id)
    return


def get_using_shops():
    total, cur_list = shop_dao.query_shops_all()
    datas = []
    for i in cur_list:
        datas.append({'id': i.id, 'code': i.code, 'shop_name': i.shop_name})
    return {'total': total, 'datas': datas}


def create_shop(code: int, shop_name: str):
    shop_dao.batch_insert([ut.Shop(code=code, shop_name=shop_name)])
    return "创建成功"


def get_shops(page_num: int, page_size: int):
    count, cur_list = shop_dao.query_shops(page_num, page_size)
    shops = []
    for i in cur_list:
        shops.append(view_wo.ShopData(id=i.id, code=i.code, shop_name=i.shop_name))
    return view_wo.DetailsResponse(total=count, datas=shops)
